<template>
  <popup class="popup" v-model:visible="visiblePopup" height="70%">
    <template #content>
      <view class="content">
        <view class="header">
          <span class="add-address"><uni-icons type="compose" size="20"></uni-icons> 新增地址</span>
          <span class="import-from-wx-address-book"
            ><uni-icons custom-prefix="iconfont" type="icon-daoru" size="16" color="#747474"></uni-icons>
            从微信导入
          </span>
        </view>
        <view class="body">
          <uni-forms :model="addressBookForm" :rules="rules" ref="formRef">
            <uni-forms-item label="地址" name="detailAddress" required>
              <view class="address-area">
                <span :style="{ color: addressBookForm.detailAddress ? '#666' : '#b9b9b9' }">{{
                  getShowAddressName() ?? '获取地址 ☞'
                }}</span>
                <span class="get-address" @click="toChooseLocation"
                  ><uni-icons type="location" size="20" color="#37ac75"></uni-icons>
                  {{ addressBookForm.detailAddress ? '修改地址' : '选择地址' }}</span
                >
              </view>
            </uni-forms-item>
            <uni-forms-item label="门牌号" name="specificAddress">
              <uni-easyinput type="text" v-model="addressBookForm.specificAddress" placeholder="详细地址, 例1层101室" />
            </uni-forms-item>
            <uni-forms-item label="标签" name="label">
              <uni-data-checkbox
                mode="tag"
                v-model="addressBookForm.label"
                selectedColor="#37ac75"
                :localdata="labelData"
              ></uni-data-checkbox>
            </uni-forms-item>
            <uni-forms-item label="姓名" required name="consignee">
              <uni-easyinput type="text" v-model="addressBookForm.consignee" placeholder="请输入收货人姓名" />
              <view>
                <uni-data-checkbox
                  selectedColor="#37ac75"
                  v-model="addressBookForm.sex"
                  required
                  mode="tag"
                  :localdata="[
                    { text: '先生', value: 1 },
                    { text: '女士', value: 0 }
                  ]"
                />
              </view>
            </uni-forms-item>
            <uni-forms-item required label="手机号" name="phone">
              <uni-easyinput type="number" v-model="addressBookForm.phone" placeholder="请填写收货手机号码 " />
            </uni-forms-item>
          </uni-forms>
          <view class="button-group">
            <button @click="submit" class="submit">保存</button>
          </view>
        </view>
      </view>
    </template>
  </popup>
</template>

<script setup lang="ts">
import Popup from '@/components/popup/index.vue'
import { ref, watch } from 'vue'
import { AddressBook } from '@/types/entity/AddressBook'
import $API from '@/api'
import PropertiesCopyUtils from '@/utils/PropertiesCopyUtils'
const props = defineProps({
  latitude: {
    type: Number
  },
  longitude: {
    type: Number
  },
  form: {
    type: AddressBook
  }
})
const emits = defineEmits<{
  (e: 'update:form', newVal: AddressBook | undefined): void
  (e: 'save'): void
}>()
const addressBookForm = ref(new AddressBook())
watch(
  () => props.form,
  (newVal, oldVal) => {
    if (newVal == null) return
    addressBookForm.value = PropertiesCopyUtils.copy([newVal], new AddressBook())
    visiblePopup.value = true
  }
)
// 表单可见
const visiblePopup = ref(false)
watch(
  () => visiblePopup.value,
  (newVal) => {
    // 如果隐藏了，将form置空
    if (!newVal) emits('update:form', undefined)
  }
)
const labelData = ref([
  { text: '家', value: '家' },
  { text: '学校', value: '学校' },
  { text: '公司', value: '公司' },
  { text: '不指定', value: '' }
])
const rules = ref({
  // 对name字段进行必填验证
  consignee: {
    // name 字段的校验规则
    rules: [
      // 校验 name 不能为空
      {
        required: true,
        errorMessage: '请填写姓名'
      }
    ],
    validateTrigger: 'submit'
  },
  phone: {
    rules: [
      {
        required: true,
        errorMessage: '请输入联系人的手机号码'
      },
      { pattern: /^1[0-9]{10}$/, errorMessage: '手机号格式不正确' }
    ],
    validateTrigger: 'submit'
  },
  detailAddress: {
    rules: [
      {
        required: true,
        errorMessage: '请获取地址信息'
      }
    ],
    validateTrigger: 'submit'
  }
})
const formRef = ref()

// 点击保存地址时
function submit() {
  formRef.value
    .validate()
    .then(async (res: any) => {
      // 保存
      const result = await $API.addressBook.save(addressBookForm.value)
      if (result.success) {
        visiblePopup.value = false
      }
      emits('save')
    })
    .catch((err: any) => {
      console.log('err', err)
    })
}
// 获取显示的地址名
function getShowAddressName() {
  if (addressBookForm.value.detailAddress == null) return null
  return (addressBookForm.value.districtName ?? '') + addressBookForm.value.detailAddress
}

// 点击去获取地址
function toChooseLocation() {
  uni.chooseLocation({
    success: async (res) => {
      const geoParseResult = await $API.thirdParty.parseGEO(res.longitude, res.latitude)
      PropertiesCopyUtils.copy([geoParseResult], addressBookForm.value)
      console.log(geoParseResult, '-->', addressBookForm.value)
    }
  })
}

defineExpose({
  visiblePopup
})
</script>

<style scoped lang="scss">
.content {
  $header-height: 80rpx;

  display: flex;
  justify-content: center;
  box-sizing: border-box;
  flex-direction: column;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 30rpx;
    width: 100%;
    height: $header-height;
    border-bottom: 1px solid rgb(224 224 224);
    line-height: $header-height;
    box-sizing: border-box;
    color: #747474;

    .add-address {
      font-weight: 700;
    }

    .import-from-wx-address-book {
      padding: 5rpx 15rpx;
      height: 40rpx;
      font-size: 28rpx;
      border: 1px solid #9c9c9c;
      border-radius: 10rpx;
      line-height: 40rpx;
    }
  }

  .body {
    position: absolute;
    inset: $header-height 0 0 0;
    overflow: auto;
    padding: 20rpx 30rpx;
    box-sizing: border-box;

    .address-area,
    .multiple-form-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 100%;
      line-height: 100%;
      line-height: 20px;
      font-size: 14px;

      .get-address {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 10rpx 15rpx;
        border: 1px solid #37ac75;
        border-radius: 10rpx;
        white-space: nowrap;
        color: #37ac75;
      }
    }

    .submit {
      margin: 0 auto;
      padding: 0 60rpx;
      height: 70rpx;
      font-size: 35rpx;
      color: #fff;
      background-color: #37ac75;
      line-height: 70rpx;
    }

    .button-group {
      display: flex;
      justify-content: center;
    }
  }
}
</style>
